import {Consts, createAPI} from './fetchRequest';

const host = __HOST__ || 'http://localhost:8088';

export function createUrl(url) {
  if (url.indexOf('http') >= 0) {
    return url;
  }
  if (url) {
    return `${host}/${url}`;
  }
  return host;
}

function filterNullAndUndefined(obj) {
  if (Array.isArray(obj)) {
    return obj;
  }
  if (obj && Object.keys(obj).length > 0) {
    const ret = {};
    Object.keys(obj).forEach((key) => {
      const val = obj[key];
      if (val !== null && val !== undefined) {
        ret[key] = val;
      }
    });
    return ret;
  }
}

function fetchRequest(HttpMethod, url, params, options) {
  const defaultOptions = {
    mode: 'cors',
    credentials: 'include',
    headers: {
      'x-requested-with': 'XMLHttpRequest'
    }
  };

  if (params) {
    defaultOptions.body = filterNullAndUndefined(params);
  }

  const requestOptions = Object.assign({}, defaultOptions, options);
  const contentType = requestOptions.headers['Content-Type'];

  if (contentType && contentType === 'application/json' && requestOptions.body) {
    requestOptions.body = JSON.stringify(requestOptions.body);
  }

  const request = createAPI(HttpMethod, createUrl(url), requestOptions);
  return request();
}

export default {
  get(url, params = {}, options = {}) {
    return fetchRequest(Consts.HttpMethods.GET, url, params, options);
  },
  post(url, params = {}, options = {}) {
    const headers = {
      'Content-Type': 'application/json'
    };
    return fetchRequest(Consts.HttpMethods.POST, url, params, Object.assign({headers}, options));
  },
  put(url, params = {}, options = {}) {
    const headers = {
      'Content-Type': 'application/json'
    };
    return fetchRequest(Consts.HttpMethods.PUT, url, params, Object.assign({headers}, options));
  },
  delete(url, params = {}, options = {}) {
    const headers = {
      // 'Content-Type': 'application/json'
    };
    return fetchRequest(Consts.HttpMethods.DELETE, url, params, Object.assign({headers}, options));
  },
};
